package com.xp.tinyurl.service.thirdprovider.impl;

import com.xp.tinyurl.service.thirdprovider.vo.UomgURLConvertResult;
import com.xp.tinyurl.service.thirdprovider.ShorterUrlService;
import com.xp.tinyurl.common.utils.OkHttp3Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */
@Service
public class UomgShorterUrlService implements ShorterUrlService {
    private static final Logger logger = LoggerFactory.getLogger(UomgShorterUrlService.class);

    private static final String UOMG_SHORT_URL_API_URL = "https://api.uomg.com/api/long2dwz";

    private static final String HTTP = "http";
    private static final String HTTPS = "https";

    @Override
    public String shorter(String longUrl) {
        String shortUrl = null;
        Map<String, String> paramMap = new HashMap<>(2);
        paramMap.put("dwzapi", "urlcn");
        paramMap.put("url", longUrl);
        try {
            String result = OkHttp3Utils.get(UOMG_SHORT_URL_API_URL, paramMap);
            /**
             * 垃圾UomgAPI, 正确转换CODE=1, 转换错误CODE也为1， 返回有false, 居然还有html代码，真神！
             */
            UomgURLConvertResult uomgResult = JSON.parseObject(result, new TypeReference<UomgURLConvertResult>() {
            });
            if (uomgResult != null) {
                shortUrl = uomgResult.getAe_url();
            }
            boolean isValidUrl = (shortUrl != null) && (shortUrl.startsWith(HTTP) || shortUrl.startsWith(HTTPS));
            if (!isValidUrl) {
                logger.error("Uomg short url failed: {}", shortUrl);
                shortUrl = null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return shortUrl;
    }

}
